import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel, QLineEdit, QProgressBar
import requests
import zipfile
from io import BytesIO
import os
import tempfile

class UpdateApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('Update Checker')
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)
        
        layout = QVBoxLayout()
        
        self.status_label = QLabel("Click to check for updates", self)
        layout.addWidget(self.status_label)
        
        self.check_button = QPushButton("Check for Updates", self)
        self.check_button.clicked.connect(self.check_for_updates)
        layout.addWidget(self.check_button)
        
        self.download_progress = QProgressBar(self)
        self.download_progress.setVisible(False)
        layout.addWidget(self.download_progress)
        
        central_widget.setLayout(layout)
        
    def check_for_updates(self):
        REPO_OWNER = "1224688280cyy"
        REPO_NAME = "mcushaoxieqi"
        ACCESS_TOKEN = "c8e7a07268225cdc2ab9b3e8171d0bf4"

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
            "Authorization": f"token {ACCESS_TOKEN}"} if ACCESS_TOKEN else {}

        try:
            # Fetch the latest release tag using authenticated request if token present
            url = f"https://gitee.com/api/v5/repos/{REPO_OWNER}/{REPO_NAME}/tags"
            response = requests.get(url, headers=headers)
            response.raise_for_status()  # Raises HTTPError for bad requests (4xx or 5xx)
            tags = response.json()
            latest_tag = tags[0]['name']
            print(f"Latest tag found: {latest_tag}")

            # Assuming 'latest' points to the latest release, adjust if needed
            download_url = f"https://gitee.com/{REPO_OWNER}/{REPO_NAME}/releases/download/latest/mcu_programmer.rar"
            
            # Inform user and proceed with download
            self.status_label.setText(f"找到新版本: {latest_tag}, 开始下载...")
            self.download_and_install(download_url, headers)
        except requests.RequestException as e:
            self.status_label.setText(f"无法下载最新的升级文件，请联系技术人员!")

    def download_and_install(self, download_url, headers={}):
        self.download_progress.setVisible(True)
        self.download_progress.setValue(0)
        tmp_file = None  # 初始化tmp_file变量
        
        try:
            with requests.get(download_url, stream=True, headers=headers) as response:
                response.raise_for_status()
                total_length = response.headers.get('content-length')
                dl = 0
                total_length = int(total_length) if total_length is not None else None
                
                with tempfile.NamedTemporaryFile(delete=False, suffix=".rar") as tmp_file:  # tmp_file在这里被重新赋值
                    for data in response.iter_content(chunk_size=40960):
                        dl += len(data)
                        tmp_file.write(data)
                        done = int(100 * dl / total_length) if total_length is not None else 100
                        self.download_progress.setValue(done)
                        QApplication.processEvents()
                    
            self.download_progress.setVisible(False)
            self.status_label.setText("最新的软件包下载成功!")
            print(f"Downloaded file saved at: {tmp_file.name}")
                    
            # Placeholder for further actions like extraction and installation
            # self.perform_installation(tmp_file.name)
        except requests.RequestException as e:
            self.status_label.setText(f"文件下载失败，请检查网络环境或者联系技术人员!")
            if tmp_file:  # 现在tmp_file在所有情况下都已定义
                os.remove(tmp_file.name)  # 清理临时文件

        else:
            # 下载成功后，复制文件到当前程序目录并恢复名称
            original_name = "mcu_programmer.rar"  # 假设原始名称为这个
            destination_path = os.path.join(os.getcwd(), original_name)
            try:
                os.replace(tmp_file.name, destination_path)
                self.status_label.setText(f"MCU刷写工具 '{original_name}' 下载成功!")
            except OSError as e:
                self.status_label.setText(f"文件从Temp缓存中移动失败，请检查是否被占用或联系技术人员!")
                os.remove(tmp_file.name)  # 如果移动失败，清理临时文件

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = UpdateApp()
    ex.show()
    sys.exit(app.exec())